package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.DeviceSelectionAdapter;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.Room;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.ui.login.LoginActivity;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.BlurBehind;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class GroupEditActivity extends BaseActivity {
	private LinearLayout mBackL;
	private Button mBackB;
	private Button mNextB;
	private EditText mNameEd;
	private ListView mDeviceLv;
	private TextView tv_statusBar_mian;
	private List<Device> mDevices = new ArrayList<Device>();
	private List<Device> mSelects = new ArrayList<Device>();
	private String name;
	private DeviceSelectionAdapter mAdapter;
	private int removeNum;
	private String deviceIds = "";
	private SVProgressHUD mSVProgressHUD;
	private int position;
	private String roomId;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_btn:
			finish();
			break;
		case R.id.nextstep:
			// finish();
			// 检查房间名字 长度以及是否存在
			deviceIds = "";
			String nameEd = mNameEd.getText().toString();
			if (nameEd.length() < 2 || nameEd.length() > 4) {
				ToastShow.Show(getApplicationContext(), getString(R.string.room_name_not_vaild));
				return;
			}
			boolean e = DeviceManager.getInstance().checkRoomExist(nameEd);
			if (e && (!name.equals(nameEd))) {
				ToastShow.Show(getApplicationContext(), getString(R.string.room_name_exsits));
				return;
			}
			// 查看房间是否有设备
			if (mSelects.size() == 0) {
				ToastShow.Show(getApplicationContext(), getString(R.string.room_no_device));
				return;
			}
			// 遍历所选择的设备 拼接ID
			// 上传房间
			mSVProgressHUD = new SVProgressHUD(this);
			mSVProgressHUD.showWithStatus("正在提交");
			// 获取所有ID
			for (int i = 0; i < mSelects.size(); i++) {
				if (i != mSelects.size() - 1) {
					deviceIds += mSelects.get(i).getDeviceID() + ",";
				} else {
					deviceIds += mSelects.get(i).getDeviceID();
				}
			}
			Log.i("wmy", "所选设备有" + deviceIds);
			if (position < 0) {
				// 上传房间 返回房间ID再上传房间里的设备
				upLoadRoom(nameEd);
			} else {
				// // 上传房间 返回房间ID再上传房间里的设备 再删除当前房间
				upLoadRoom1(nameEd);
			}
			break;

		default:
			break;
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				upLoadDeviceInRoom(msg.arg1);
				break;
			case 1:
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				ToastShow.Show(getApplicationContext(), msg.obj.toString());
				break;
			case 2:
				// 向服务器请求房间数据
				getAllRooms();
				// Log.i("wmy", "添加成功");
				// if (mSVProgressHUD.isShowing()) {
				// mSVProgressHUD.dismiss();
				// }
				// ToastShow.Show(getApplicationContext(),
				// getString(R.string.addedsuccess));
				// finish();
				break;
			case 3:
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				ToastShow.Show(getApplicationContext(), msg.obj.toString());
				break;
			case 4:
				Log.i("wmy", "添加成功");
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				ToastShow.Show(getApplicationContext(), getString(R.string.addedsuccess));
				finish();
				break;
			case 5:
				upLoadDeviceInRoom1(msg.arg1);
				break;
			case 6:
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				ToastShow.Show(getApplicationContext(), msg.obj.toString());
				break;
			case 7:
				// 上传设备ID成功，根据RoomId删除组别
				deleteRoom(roomId);
				break;
			case 8:
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				ToastShow.Show(getApplicationContext(), msg.obj.toString());
				break;
			default:
				break;
			}
		}
	};

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_group_edit;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		BlurBehind.getInstance()
				// .withAlpha(80)
				// .withFilterColor(Color.parseColor("#000000"))
				.setBackground(this);
		tv_statusBar_mian = $(R.id.tv_statusBar_mian);
		boolVersion();
		mBackL = $(R.id.back_layout);
		mBackL.setVisibility(View.GONE);
		mBackB = $(R.id.back_btn);
		mBackB.setVisibility(View.VISIBLE);
		mNextB = $(R.id.nextstep);
		mNextB.setText(getString(R.string.ok));
		mNextB.setVisibility(View.VISIBLE);
		mDeviceLv = $(R.id.device_lv);
		mNameEd = $(R.id.name_ed);
		mBackB.setOnClickListener(this);
		mNextB.setOnClickListener(this);
		mDeviceLv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				// TODO Auto-generated method stub
				boolean select = mDevices.get(position).isSelected();
				mDevices.get(position).setSelected(!select);
				mAdapter.notifyDataSetChanged();
				if (select) { // 已被选中 移除
					for (int i = 0; i < mSelects.size(); i++) {
						if (mSelects.get(i).getDeviceID().equals(mDevices.get(position).getDeviceID())) {
							removeNum = i; // 需要被移除的设备编号
						}
					}
					mSelects.remove(removeNum);
				} else { // 未被选中 添加
					Device device = new Device();
					device.setDeviceID(mDevices.get(position).getDeviceID());
					device.setDeviceName(mDevices.get(position).getDeviceName());
					if (mDevices.get(position).getDeviceAddress() != null) {
						device.setDeviceAddress(mDevices.get(position).getDeviceAddress());
					}
					mSelects.add(device);
				}
			}
		});
		initData();
	}

	private void initData() {
		// TODO Auto-generated method stub
		position = getIntent().getIntExtra("position", -1);
		mDevices = DeviceManager.getInstance().getNoLockDevice();
		if (position >= 0) {
			Log.i("wmy", "需要加载 true 获取position" + position);
			name = DeviceManager.getInstance().getRooms().get(position).getRoomName();
			roomId = DeviceManager.getInstance().getRooms().get(position).getRoomId();
			mNameEd.setText(name);
			mNameEd.setSelection(name.length());
			mSelects = DeviceManager.getInstance().getRooms().get(position).getDevices();
			for (int i = 0; i < mDevices.size(); i++) {
				for (int j = 0; j < mSelects.size(); j++) {
					mDevices.get(i).setSelected(false);
					if (mSelects.get(j).getDeviceID().equals(mDevices.get(i).getDeviceID())) {
						mDevices.get(i).setSelected(true);
						break;
					}
				}
			}
		} else {
			Log.i("wmy", "全部设为false 获取position" + position);
			for (int i = 0; i < mDevices.size(); i++) {
				mDevices.get(i).setSelected(false);
			}
		}
		mAdapter = new DeviceSelectionAdapter(getApplicationContext(), mDevices);
		mDeviceLv.setAdapter(mAdapter);
	}

	private void upLoadRoom(String name) {
		RequestParams params = new RequestParams(HttpURL.ADD_ROOM_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("roomName", name);
			obj.put("roomType", "8");
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));

			Log.d("Tag", " upload obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.i("Tag", result);
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					if (resultCode.equals("1")) {
						// 上传成功，保存到本地
						int data = jo.getInt("data");
						Message msg = Message.obtain();
						msg.what = 0;
						msg.arg1 = data;
						mHandler.sendMessage(msg);
					} else {
						String errorMsg = jo.optString("errorMsg");
						Message msg = Message.obtain();
						msg.what = 1;
						msg.obj = errorMsg;
						mHandler.sendMessage(msg);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void upLoadRoom1(String name) {
		RequestParams params = new RequestParams(HttpURL.ADD_ROOM_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("roomName", name);
			obj.put("roomType", "8");
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));

			Log.d("Tag", " upload obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.i("Tag", result);
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					if (resultCode.equals("1")) {
						// 上传成功，保存到本地
						int data = jo.getInt("data");
						Message msg = Message.obtain();
						msg.what = 5;
						msg.arg1 = data;
						mHandler.sendMessage(msg);
					} else {
						String errorMsg = jo.optString("errorMsg");
						Message msg = Message.obtain();
						msg.what = 6;
						msg.obj = errorMsg;
						mHandler.sendMessage(msg);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void deleteRoom(String roomId) {
		RequestParams params = new RequestParams(HttpURL.DELETE_ROOM_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("roomId", roomId);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));

			Log.d("Tag", " upload obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.i("Tag", result);
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					if (resultCode.equals("1")) {
						// 上传成功，保存到本地
						Message msg = Message.obtain();
						msg.what = 2;
						mHandler.sendMessage(msg);
					} else {
						String errorMsg = jo.optString("errorMsg");
						Message msg = Message.obtain();
						msg.what = 8;
						msg.obj = errorMsg;
						mHandler.sendMessage(msg);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void upLoadDeviceInRoom(int roomId) {
		RequestParams params = new RequestParams(HttpURL.UPDATE_ROOM_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("deviceIdS", deviceIds);
			obj.put("roomId", roomId);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));

			Log.d("Tag", " upload obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.i("Tag", result);
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					if (resultCode.equals("1")) {
						// 上传成功，保存到本地
						// int data = jo.getInt("data");
						Message msg = Message.obtain();
						msg.what = 2;
						mHandler.sendMessage(msg);
					} else {
						String errorMsg = jo.optString("errorMsg");
						Message msg = Message.obtain();
						msg.what = 3;
						msg.obj = errorMsg;
						mHandler.sendMessage(msg);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void upLoadDeviceInRoom1(int roomId) {
		RequestParams params = new RequestParams(HttpURL.UPDATE_ROOM_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("deviceIdS", deviceIds);
			obj.put("roomId", roomId);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));

			Log.d("Tag", " upload obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.i("Tag", result);
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					if (resultCode.equals("1")) {
						// 上传成功，保存到本地
						// int data = jo.getInt("data");
						Message msg = Message.obtain();
						msg.what = 7;
						mHandler.sendMessage(msg);
					} else {
						String errorMsg = jo.optString("errorMsg");
						Message msg = Message.obtain();
						msg.what = 8;
						msg.obj = errorMsg;
						mHandler.sendMessage(msg);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			tv_statusBar_mian.setLayoutParams(layoutParams1);
			tv_statusBar_mian.setVisibility(View.VISIBLE);

		} else {
			tv_statusBar_mian.setVisibility(View.GONE);
		}
	}

	public void getAllRooms() {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_ROOM_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("hid", DeviceManager.getInstance().hid);
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
				Log.d("test", " get all rooms = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					DeviceManager.getInstance().clearRoom();
					Log.e("wmy", "get all =" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							JSONArray data = jsonObject.getJSONArray("data");
							Log.e("wmy", "length " + data.length());
							if (data.length() != 0) {
								for (int i = 0; i < data.length(); i++) {
									JSONObject jo = data.getJSONObject(i);
									String roomId = jo.getString("roomId");
									String roomName = jo.optString("roomName");
									List<Device> deviceses = new ArrayList<Device>();
									JSONArray ja = jo.getJSONArray("deviceses");
									for (int j = 0; j < ja.length(); j++) {
										int deviceType = ja.getJSONObject(j).getInt("deviceType");
										String deviceId = ja.getJSONObject(j).getString("deviceId");// deviceName
										String deviceMac = ja.getJSONObject(j).optString("deviceMac");
										Log.i("wmy", "group deviceMac = "+deviceMac);
										int status = ja.getJSONObject(j).getInt("nurdStatus");
										String deviceName = ja.getJSONObject(j).getString("remarks");
										Log.i("wmy", "group device = "+deviceName);
										Device device = new Device(deviceId, deviceMac, deviceName, deviceType, status);
										deviceses.add(device);
										Log.i("wmy", "添加一个device"+deviceName);
									}
									Room room = new Room(roomId, roomName, deviceses);
									DeviceManager.getInstance().setGroupChildDevices(roomId, deviceses);
									DeviceManager.getInstance().addRoom(room);
								}
							}
							Log.i("wmy", "准备发送消息");
							Message msg = Message.obtain();
							msg.what = 4;
							mHandler.sendMessage(msg);
							Log.i("wmy", "已发送消息");
						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							ToastShow.Show(getApplicationContext(), "您的登陆已超时，请重新登陆");
							startActivity(new Intent(getApplicationContext(), LoginActivity.class));
							finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}
}
